package cn.bjit.service.impl;

import cn.bjit.component.SmsComponent;
import cn.bjit.config.SmsConfig;
import cn.bjit.constant.RedisKey;
import cn.bjit.enums.BizCodeEnum;
import cn.bjit.enums.SendCodeEnum;
import cn.bjit.service.NotifyService;

import cn.bjit.util.CheckUtil;
import cn.bjit.util.CommonUtil;
import cn.bjit.util.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class NotifyServiceImpl implements NotifyService {
   //10分钟
    private  static final int CODE_EXPIRED=60*10*1000;
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SmsComponent smsComponent;
    @Autowired
    private SmsConfig smsConfig;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 发送短信验证码
     * @param sendCodeEnum
     * @param to
     * @return
     */
    @Override
    public JsonData sendCode(SendCodeEnum sendCodeEnum, String to) {
        //填充key
        String captchKey=String.format(RedisKey.CHECK_CODE_KEY,sendCodeEnum.name(),to);

        String captchValue=redisTemplate.opsForValue().get(captchKey);
//       如果不是null ,判断是否是60秒 重复发送
        if(StringUtils.isNotBlank(captchValue)){
           Long ttl= Long.parseLong(captchValue.split("_")[1]);
           Long leftTime=CommonUtil.getCurrentTimestamp()-ttl;
           if(leftTime<(1000*60)){ //60000
               log.info("重复发送短信验证码，时间间隔是：{}秒",leftTime);
               return JsonData.buildResult(BizCodeEnum.CODE_LIMITED);
           }
        }

        String code=CommonUtil.getRandomCode(6);
         //拼接验证码
        String value= code+"_"+CommonUtil.getCurrentTimestamp();
        redisTemplate.opsForValue().set(captchKey,value,CODE_EXPIRED,TimeUnit.MILLISECONDS);

        if(CheckUtil.isEmail(to)){
             //发送邮箱验证码 TODO
        }else if(CheckUtil.isPhone(to)){ //验证手机号码
            smsComponent.send(to,smsConfig.getTemplateId(),code);
            log.info("=====>验证码是=={}=====",code);
        }
        return JsonData.buildSuccess();
    }

    /**
     * 校验验证码
     * @param sendCodeEnum
     * @param to
     * @param code
     * @return
     */
    public boolean checkCode(SendCodeEnum sendCodeEnum, String to, String code) {
        String captchKey=String.format(RedisKey.CHECK_CODE_KEY,sendCodeEnum.name(),to);
        String captValue= redisTemplate.opsForValue().get(captchKey);
        //123456_121212121
        if(StringUtils.isNotBlank(captValue)){
           String captCode=captValue.split("_")[0];
           if(captCode.equalsIgnoreCase(code)){
               redisTemplate.delete(code);
               return true;
           }
        }
        return false;
    }

    // @Async("threadPoolTaskExecutor")
//    @Async
//    public void testSend() {
//
//        try {
//            TimeUnit.MILLISECONDS.sleep(2000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        log.info("====================================");
//        ResponseEntity<String> forEntity = restTemplate.getForEntity("", String.class);
//        String body = forEntity.getBody();
//        log.info(body);
//    }
}
